<template>
  <table-row-detail-dialog
    ref="detailDialog"
    :dialog-title="'上传文件'"
    @confirm="handleConfirm"
  >
    <div class="dialog-body">
      <el-form
        :model="formData"
        ref="detailForm"
        :rules="rules"
        label-width="90px"
      >
        <el-form-item class="file-name" label="文件名称" prop="mediaName">
          <el-input
            type="text"
            v-model="formData.mediaName"
            placeholder="由英文字母、数字及特殊符号、下划线、空格、汉字组成"
          ></el-input>
        </el-form-item>
        <el-form-item label="上传文件" prop="fileName">
          <el-input
            type="text"
            style="display: none"
            v-model="formData.fileName"
          ></el-input>
          <el-upload
            class="upload-demo"
            style="width: 80%"
            drag
            :multiple="false"
            :limit="1"
            :action="actionUrl"
            :headers="headers"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :before-upload="beforeAvatarUpload"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              仅支持上传一个文件<br />
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              支持的格式包括:<br />
              1、图片：png、jpg、jpeg、gif、bmp、webp;<br />
              2、视频：mp4、mov、avi<br />
              3、音频：mp3、wav、m4a、flac、aac <br />
              4、文档：pdf、doc、docx、xls、xlsx、ppt、pptx
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
  </table-row-detail-dialog>
</template>

<script>
import TableRowDetailDialog from '@/components/TableRowDetailDialog/index';
import FormItemGroup from '@/components/FormItemGroup/index';
import { basePath, filePathPrefix } from '@/utils/request';
import { add as localAdd } from '@/api/serve/media-local';
import { add as teamAdd } from '@/api/serve/media-team';
import { getToken } from '@/utils/auth';

export default {
  name: 'ItemDetail',
  components: {
    TableRowDetailDialog,
    FormItemGroup,
  },
  props: {},
  data() {
    return {
      action: 'detail',
      itemData: null, //详情数据
      formData: {}, //表单数据
      id: '',
      catalogId: '',
      file: null,
      actionUrl: basePath + 'media/file',
      rules: {
        mediaName: [
          { required: true, message: '文件名称不能为空' },
          {
            validator: function (rule, value, callback) {
              if (
                /^[^\s\d?？/*<>|][a-zA-Z0-9￥@&+()《》、""【】\[\]\-\—.。_\s\u4e00-\u9fa5]{0,59}$/.test(
                  value
                ) == false
              ) {
                callback(
                  new Error(
                    '文件名称不合法，不允许出现“？”、“/”、“*”、“<”、“>”、“|”等特殊符号及空格、数字开头'
                  )
                );
              } else {
                //校验通过
                callback();
              }
            },
            trigger: 'blur',
          },
        ],
        fileName: [{ required: true, message: '不能为空，请上传文件' }],
      },
      menuType: 'local',
    };
  },
  computed: {
    headers() {
      let token = getToken();
      return token ? { Authorization: token } : {};
    },
  },
  created() {},
  methods: {
    // 文件上传前的校验 —— 常见的校验有：校验文件类型，文件大小
    beforeAvatarUpload(file) {
      // 允许上传的文件格式列表
      let acceptList = [
        'png',
        'jpg',
        'jpeg',
        'gif',
        'bmp',
        'webp',
        'mp4',
        'mov',
        'avi',
        'mp3',
        'wav',
        'm4a',
        'flac',
        'aac',
        'pdf',
        'doc',
        'docx',
        'xls',
        'xlsx',
        'ppt',
        'pptx',
      ];
      // 根据文件名获取文件的后缀名
      let fileType = file.name.split('.').pop().toLowerCase();
      // 判断文件格式是否符合要求
      if (acceptList.indexOf(fileType) === -1) {
        this.$message.error(
          '请按照提示上传文件，不能上传 ' + fileType + ' 格式!'
        );
        return false;
      }
    },
    show(dialogType = 'detail', data, menuType) {
      this.menuType = menuType;
      this.dialogType = dialogType;
      this.catalogId = data.catalogId;

      this.initFormData();
      this.$refs.detailDialog.show(dialogType);
    },
    /**
     * 初始化表单数据
     * */
    initFormData() {
      this.formData = {
        mediaName: '',
        fileName: '',
      };
    },
    handleSuccess(res, file, fileList) {
      if (!!res.code) {
        this.handleError(res);
      } else {
        this.file = file;
        this.formData.fileName = this.formData.mediaName = res.name.substring(
          0,
          res.name.lastIndexOf('.')
        );
        this.$refs.detailForm.validate((valid) => {
          if (valid) {
          } else {
            return false;
          }
        });
      }
    },
    handleRemove(file, fileList) {
      this.file = null;
      this.formData.fileName = '';
    },
    handleError(err, file, fileList) {
      this.$message.closeAll();
      this.$message.error('文件上传失败，请重试');
      this.$emit('upload-error', err);
    },

    /**
     * 对话框确认按钮响应
     * */
    handleConfirm() {
      let that = this;
      this.$refs.detailForm.validate((valid) => {
        if (valid) {
          if (!that.file) {
            that.$message.warning('未上传文件');
            return false;
          }
          let data = {
            catalogId: that.catalogId,
            fileId: that.file.response.id,
            mediaName: that.formData.mediaName,
          };

          if (that.menuType === 'local') {
            localAdd(data).then((res) => {
              that.submitSuccess();
            });
          } else if (that.menuType === 'team') {
            teamAdd(data).then((res) => {
              that.submitSuccess();
            });
          }
        } else {
          return false;
        }
      });
    },
    /**
     * 记录详情数据修改提交成功，触发data-change消息更新列表数据
     */
    submitSuccess() {
      this.$message.success('上传成功!');
      this.hide();
      this.$emit('data-change');
    },
    /**
     * 隐藏对话框
     */
    hide() {
      this.$refs.detailDialog.hide();
      this.$emit('dialog-close');
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 18px 0 !important;
  .el-input {
    width: 80%;
  }
}
.file-name {
  margin-bottom: 39px !important;
}
</style>
